import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, Modal, message, Form, Input, InputNumber, Select, Upload } from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ExclamationCircleOutlined,
  UploadOutlined 
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { CustomTable } from '../../g-component/CustomTable';
import { ProductListApi, Product, ProductStatus } from './server';
import './index.less';

const { confirm } = Modal;
const { Option } = Select;
const { TextArea } = Input;

/**
 * 商品状态标签
 */
const ProductStatusTag: React.FC<{ status?: ProductStatus }> = ({ status }) => {
  switch(status) {
    case ProductStatus.OnSale:
      return <Tag color="success">在售</Tag>;
    case ProductStatus.OutOfStock:
      return <Tag color="default">缺货</Tag>;
    case ProductStatus.Discontinued:
      return <Tag color="error">已下架</Tag>;
    default:
      return <Tag color="processing">草稿</Tag>;
  }
};

/**
 * 商品列表内容组件 - 不包含布局
 */
export const ProductListContent: React.FC = () => {
  // 商品列表数据
  const [productList, setProductList] = useState<Product[]>([]);
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  // 分页信息
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  // 搜索关键字
  const [keyword, setKeyword] = useState<string>('');
  // 编辑商品的表单
  const [form] = Form.useForm();
  // 是否显示编辑Modal
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
  // 当前编辑的商品
  const [currentProduct, setCurrentProduct] = useState<Product | null>(null);

  // 获取商品列表
  const fetchProductList = async (page = pagination.current, pageSize = pagination.pageSize, search = keyword) => {
    try {
      setLoading(true);
      const result = await ProductListApi.getProductList({
        page,
        pageSize,
        keyword: search,
      });
      setProductList(result.list);
      setPagination({
        ...pagination,
        current: page,
        total: result.total,
      });
    } catch (error) {
      console.error('获取商品列表失败', error);
      message.error('获取商品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchProductList();
  }, []);

  // 处理表格变更
  const handleTableChange = (page: number, pageSize?: number) => {
    fetchProductList(page, pageSize);
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setKeyword(value);
    fetchProductList(1, pagination.pageSize, value);
  };

  // 处理添加/编辑商品
  const handleAddOrEditProduct = () => {
    setCurrentProduct(null);
    form.resetFields();
    setEditModalVisible(true);
  };

  // 处理编辑商品
  const handleEditProduct = (product: Product) => {
    setCurrentProduct(product);
    form.setFieldsValue({
      name: product.name,
      code: product.code,
      category: product.category,
      price: product.price,
      stock: product.stock,
      description: product.description,
      status: product.status,
    });
    setEditModalVisible(true);
  };

  // 处理删除商品
  const handleDeleteProduct = (product: Product) => {
    confirm({
      title: '确定要删除此商品吗?',
      icon: <ExclamationCircleOutlined />,
      content: '删除后无法恢复',
      onOk: async () => {
        try {
          await ProductListApi.deleteProduct(product.id);
          message.success('删除成功');
          fetchProductList();
        } catch (error) {
          console.error('删除商品失败', error);
          message.error('删除商品失败');
        }
      },
    });
  };

  // 保存商品信息
  const handleSaveProduct = async () => {
    try {
      const values = await form.validateFields();
      if (currentProduct) {
        // 编辑商品
        await ProductListApi.updateProduct({
          id: currentProduct.id,
          ...values,
        });
        message.success('更新商品成功');
      } else {
        // 新增商品
        await ProductListApi.createProduct(values);
        message.success('创建商品成功');
      }
      setEditModalVisible(false);
      fetchProductList();
    } catch (error) {
      console.error('保存商品失败', error);
      message.error('保存商品失败');
    }
  };

  // 图片上传配置
  const uploadProps: UploadProps = {
    name: 'file',
    action: '/api/upload',
    headers: {
      authorization: 'authorization-text',
    },
    onChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  // 表格列定义
  const columns = [
    {
      title: '商品图片',
      dataIndex: 'image',
      key: 'image',
      render: (image?: string) => (
        image ? <img src={image} alt="商品图片" style={{ width: 50, height: 50, objectFit: 'cover' }} /> : '-'
      ),
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '商品编码',
      dataIndex: 'code',
      key: 'code',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price?: number) => price ? `¥${price.toFixed(2)}` : '-',
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status?: ProductStatus) => <ProductStatusTag status={status} />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: Product) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditProduct(record)}
          >
            编辑
          </Button>
          <Button 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeleteProduct(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div className="product-list-container">
      <h2 className="page-title">商品管理</h2>

      <Card bordered={false}>
        <div className="table-operations">
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={handleAddOrEditProduct}
          >
            新增商品
          </Button>
        </div>
        
        <CustomTable<Product>
          columns={columns}
          dataSource={productList}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            onChange: handleTableChange,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
          }}
          showSearch
          searchPlaceholder="搜索商品名称、编码"
          onSearch={handleSearch}
          showRefresh
          onRefresh={() => fetchProductList()}
        />
      </Card>

      {/* 编辑商品弹窗 */}
      <Modal
        title={currentProduct ? '编辑商品' : '新增商品'}
        open={editModalVisible}
        onOk={handleSaveProduct}
        onCancel={() => setEditModalVisible(false)}
        maskClosable={false}
        destroyOnClose
        width={600}
      >
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          layout="horizontal"
        >
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>
          
          <Form.Item
            name="code"
            label="商品编码"
            rules={[{ required: true, message: '请输入商品编码' }]}
          >
            <Input placeholder="请输入商品编码" />
          </Form.Item>
          
          <Form.Item
            name="category"
            label="分类"
            rules={[{ required: true, message: '请选择商品分类' }]}
          >
            <Select placeholder="请选择商品分类">
              <Option value="电子产品">电子产品</Option>
              <Option value="服装">服装</Option>
              <Option value="家居">家居</Option>
              <Option value="食品">食品</Option>
              <Option value="图书">图书</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="price"
            label="价格"
            rules={[{ required: true, message: '请输入商品价格' }]}
          >
            <InputNumber 
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="请输入商品价格"
              prefix="¥"
            />
          </Form.Item>
          
          <Form.Item
            name="stock"
            label="库存"
            rules={[{ required: true, message: '请输入库存数量' }]}
          >
            <InputNumber
              min={0}
              style={{ width: '100%' }}
              placeholder="请输入库存数量"
            />
          </Form.Item>
          
          <Form.Item
            name="image"
            label="商品图片"
          >
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>
          
          <Form.Item
            name="description"
            label="商品描述"
          >
            <TextArea 
              rows={4}
              placeholder="请输入商品描述"
            />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择商品状态' }]}
          >
            <Select placeholder="请选择商品状态">
              <Option value={ProductStatus.Draft}>草稿</Option>
              <Option value={ProductStatus.OnSale}>在售</Option>
              <Option value={ProductStatus.OutOfStock}>缺货</Option>
              <Option value={ProductStatus.Discontinued}>已下架</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}; 